from django.contrib import admin
from .models import *
from django.forms import TextInput, Textarea
from django.utils.text import capfirst # 分类排序


# from cryptography.fernet import Fernet
from django.db.models import Q
from django.conf import settings

@admin.register(Host)
class Host_admin(admin.ModelAdmin):
    all_fields = list(key.name for key in Host._meta.fields ) # 变量字段排除id
    list_display = all_fields
    
    search_fields = ['hostname', 'ip','floatingip',  'ipv6']
    list_filter = ['region_id','platform_id']  # 右侧过滤栏
    list_editable = ['status']  # 可编辑项
    list_per_page = 25  # 每页显示条数
    ordering = ['-gmt_modified']

    fieldsets = (
        ('主机信息', {
            'fields': ['hostname', 'ip', 'ssh_id','department']
        }),
        ('云平台', {
            # 'classes': ('collapse',),  # 隐藏显示
            'fields': ['instance_id', 'floatingip','ipv6', 'region_id', 'platform_id']
        }),
        ('硬件信息', {
            # 'classes': ('collapse', ),  # 隐藏显示
            'fields': ['cpu', 'memory', 'disk']
        }),
         ('其他信息', {
            # 'classes': ('collapse', ),  # 隐藏显示
            'fields': ('os_version','tag','status', 'desc'),
        }),
    )

    formfield_overrides = {
        models.CharField: {'widget': TextInput(attrs={'size': '20'})},
        models.TextField: {'widget': Textarea(attrs={'rows': 4, 'cols': 60})},
    }

    # 新增或修改数据时，过滤外键可选值
    # def formfield_for_foreignkey(self, db_field, request, **kwargs):
    #     if db_field.name == 'ssh_id':
    #         # 过滤判断
    #         kwargs["queryset"] =  SSH_account.objects.filter(is_manager=True)
    #     return super().formfield_for_foreignkey(db_field, request, **kwargs)

@admin.register(SSH_account)
class CmdbSSH_accountadmin(admin.ModelAdmin):
    all_fields = list(key.name for key in SSH_account._meta.fields  if key.name !='id')  # 变量字段排除id
    list_display =  all_fields
    search_fields = ['name']
    list_per_page = 25  # 每页显示条数
    ordering = ['-gmt_modified']


# @admin.register(SSH_account)
# class SSH_accountadmin(admin.ModelAdmin):
#     all_fields = list(key.name for key in SSH_account._meta.fields if key.name !='id' )  # 变量字段排除id
#     list_display = all_fields  
#     # list_display = ['index','id','name', 'is_manager','port','ssh_user','is_secret','authentication_type','content']
#     search_fields = ['name']
#     list_editable = ['is_manager']
#     ordering = ['index']

#     def save_model(self, request, obj, form, change):
#         """针对明文密码和sshkey私钥对等加密"""
#         if obj.is_secret is False and  obj.authentication_type == 'Text' or obj.is_secret is False and  obj.authentication_type == 'Private':
#             # cipher_key = 'JhpsbscR9FWrCt3eWuQC3WzRpzhIxsZ70aZLruCFevg='
#             cipher_key = settings.CIPHER_KEY
#             print(cipher_key)
#             cipher = Fernet(cipher_key)
#             passwd = obj.password  # 输入密码
#             # 进行加密
#             encrypted_text = cipher.encrypt(passwd.encode())
            
#             # 进行解密
#             #encrypted_bytes = encrypted_text.encode()
#             # decrypted_text = cipher.decrypt(encrypted_bytes).decode()  
            
#             # obj.content = encrypted_text.decode() # 转字符串
            
#             obj.is_secret = 1  # 更新加密状态
#             obj.save()
#         else:
#             obj.save()

@admin.register(Region)
class CmdbRegionadmin(admin.ModelAdmin):
    all_fields = list(key.name for key in Region._meta.fields  if key.name !='id')  # 变量字段排除id
    list_display =  all_fields
    search_fields = ['city']
    list_per_page = 25  # 每页显示条数
    ordering = ['-gmt_modified']

@admin.register(Platform)
class CmdbPlatform_admin(admin.ModelAdmin):
    all_fields = list(key.name for key in Platform._meta.fields if key.name !='id' )   # 变量字段排除id
    list_display = all_fields
    search_fields = ['name']
    list_per_page = 25  # 每页显示条数

@admin.register(PlatformAccount)
class CmdbPlatform_Account_admin(admin.ModelAdmin):
    all_fields = list(key.name for key in PlatformAccount._meta.fields)
    list_display = all_fields  
    search_fields = ['name']
    list_per_page = 25  # 每页显示条数

# 标签
@admin.register(Tag)
class TagAdmin(admin.ModelAdmin):
    list_display = ('name', 'desc','get_items')
    search_fields = ('name', )
    readonly_fields = ('get_items',)
    list_per_page = 20



# 排序
def find_model_index(name):
    count = 0
    for model, model_admin in admin.site._registry.items():
        if capfirst(model._meta.verbose_name_plural) == name:
            return count
        else:
            count += 1
    return count


def index_decorator(func):
    def inner(*args, **kwargs):
        templateresponse = func(*args, **kwargs)
        for app in templateresponse.context_data['app_list']:
            app['models'].sort(key=lambda x: find_model_index(x['name']))
        return templateresponse
    return inner
admin.site.index = index_decorator(admin.site.index)
admin.site.app_index = index_decorator(admin.site.app_index)